/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import tools.UtopiaTime;
import database.DBConnectionFactory;

/**
 * Represents a farm (province with resources to steal, plunder or learn)
 * 
 * 
 */
public class Farm implements BotObject {
   /**
    * Returns a list of farms
    * 
    * @return a List of Farm objects
    */
   public static List<Farm> getFarms() {
	  List<Farm> out = new LinkedList<Farm>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM farm ORDER BY updated DESC");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new Farm(rs.getString("name"), rs.getString("loc"), rs.getString("message"), rs.getTimestamp("updated")
				  .getTime()));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String province = "";
   private String kd = "";
   private String message = "";

   private Long time = 0L;

   public Farm(final String province, final String kd, final String message, final Long time) {
	  this.province = province;
	  this.kd = kd;
	  this.message = message;
	  this.time = time;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (args.length == 1 || StringTools.isNullOrEmpty(getProvince()) || StringTools.isNullOrEmpty(getKd())
			|| StringTools.isNullOrEmpty(getMessage()) || getTime() == null) {
		 out.add(Colors.BLUE + "#" + args[0] + ": " + Colors.RED + getProvince() + " " + getKd() + Colors.NORMAL + " >> "
			   + Colors.OLIVE + getMessage() + Colors.BLUE + ". Added: " + UtopiaTime.compareTimes(getTime()) + " ago");
	  }
	  return out;
   }

   public String getKd() {
	  return kd;
   }

   public String getMessage() {
	  return message;
   }

   public String getProvince() {
	  return province;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getProvince()) || StringTools.isNullOrEmpty(getKd())
			|| StringTools.isNullOrEmpty(getMessage()) || getTime() == null)
		 return out;
	  out.put("Province", getProvince());
	  out.put("KD", getKd());
	  out.put("Message", getMessage());
	  out.put("Added Time", new Date(getTime()));
	  return out;
   }

   public Long getTime() {
	  return time;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getProvince()) || StringTools.isNullOrEmpty(getKd())
			|| StringTools.isNullOrEmpty(getMessage()) || getTime() == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM farm WHERE name = ?");
		 ps.setString(1, getProvince());
		 ps.executeUpdate();

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO farm VALUES(?,?,?,?)");
		 ps.setString(1, getProvince());
		 ps.setString(2, getKd());
		 ps.setString(3, getMessage());
		 ps.setTimestamp(4, new Timestamp(getTime()));
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setTime(final Long time) {
	  this.time = time;
   }
}
